package eu.web.security.access;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;

import eu.config.Config;
import eu.config.ConfigManager;
import eu.helper.RootPath;


public class AccessAnalyst {
	static String filepath;

	HashMap<String, Access> map;

	private static AccessAnalyst instance=new AccessAnalyst();

	public boolean check(String url,AccessIdentity id) {
		while(url!=null){
			if(map.containsKey(url)){
				return map.get(url).validate(id);
			}
			url=UpUrl(url);
		}
		return false;
	}

	private String UpUrl(String url){
		if(url.contains("/")){
			if("/".equals(url))
				return null;
			String t=url.substring(0,url.lastIndexOf("/"));
			if(t.length()==0)
				return "/";
			return t;
		}
		return null;
	}
	
	public static AccessAnalyst getInstance() {
		return instance;
	}


	private AccessAnalyst() {
		map = new HashMap<String, Access>();
		init();
	}

	private void init() {
		Config config=getConfig();
		if(config==null)
			return;
		String path;
		Access access;
		String[] group;
		String[] groups;
		List<String> keys=config.getKeys();
		for (String key:keys) {
			path=key;
			groups = config.getValueNE(key).split("\\|\\|");
			access = new Access(path);
			int gIndex=0;
			for(String groupString:groups){
				group=groupString.split(",");
				for(String power :group){
					access.addPrivilege(power, gIndex);
					System.out.println(power+" added to "+path);
				}
			}
			map.put(path, access);
		}
	}
	
	private Config getConfig(){
		Config config=null;
		try {
			config=ConfigManager.loadConfigFile(RootPath.root+"eu.web.access.conf")
				.getConfig("eu.web.access");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		if(config==null)
			config=ConfigManager.getGlobalConfig("eu.web.access");
		return config;
	}
	
}
